//
//  ZFOAuthViewController.swift
//  WeiBoAPP
//
//  Created by 张学飞 on 2019/1/18.
//  Copyright © 2019 zxf. All rights reserved.
//

import UIKit
import SVProgressHUD


class ZFOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(backAction ) ,isBack:true)
        
        let rightButton1 =  UIBarButtonItem(title: "登录", target: self, action: #selector(loginAction))
        
        let rightButton2 = UIBarButtonItem(title: "自动填充按钮", target: self, action: #selector(autoFill))
        
          navigationItem.rightBarButtonItems = [rightButton1,rightButton2]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        loadOauth2()
        webView.delegate = self
        webView.scrollView.isScrollEnabled = false
        let code =  "code=4b4561fc3702d838162aedf3ccc69da0"
        
        if code.hasPrefix("code")  == false{
            print("没有code")
        }else {
            print("有code")
        }
    }
    
    
    func loadOauth2() {
//        let urlstring = "https://api.weibo.com/oauth2/authorize?client_id=561655988&redirect_uri=http://baidu.com"

        
        let urlstring = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_APP_REDIRET_URL)"
//        let url = URL(string: urlstring)
        
        
        guard let url = URL(string: urlstring)
            else {
            return
        }
        
        let request = URLRequest(url: url)
        webView.loadRequest(request)
    }
    
    
    //返回
    @objc func backAction() {
        dismiss(animated: true) {
            
        }
    }
    
    //登录
    @objc func loginAction() {
       
        NotificationCenter.default.post(name: NSNotification.Name(WB_LoginRegistSuccess_Notification), object: nil)

        dismiss(animated: true) {
        }
    }
    
    
    @objc func autoFill() {
        
        //;表示两个语句，不能省略
        //修改本地浏览器中缓存的y页面内容 ，点击登录按钮 执行 submit() 将本地数据提交给服务器
        let js = "document.getElementById('userId').value='2540927373@qq.com';" +
            "document.getElementById('passwd').value='zxf123456';"
        webView.stringByEvaluatingJavaScript(from: js)
        
    }

    @objc func close () {
        SVProgressHUD.dismiss()
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}


extension ZFOAuthViewController : UIWebViewDelegate{
    
    /*
     *@Description: 将要加载
     *@Params: request
     *@Return:
     
     
     */
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
      
//        print("将要加载 -- \(String(describing: request.url?.absoluteString))")
        print("将要加载 查询 -- \(String(describing: request.url?.query))" )

        //如果包含WB_APP_REDIRET_URL 表示成功 查找字符串是否包含 code
        //已经成功
        if request.url?.absoluteString.hasPrefix(WB_APP_REDIRET_URL) == false {
            print("授权成功")
            return true
        }
        //取消授权
        if request.url?.query?.hasPrefix("code") == false {
            
            print("取消授权")
            return false
        }
        
        //获取授权码，不需要加载百度页面，所有false
        //获取参数字符串 (？
        let codeQueryStr = request.url?.query
        
//        let code  =  request.url?.query?.substring(from: "code=".endIndex)
        let code = codeQueryStr?["code=".endIndex ..< (codeQueryStr?.endIndex)!]

        print("code： \(String(describing: code))")
        loadAcessToken(code: String(format: "%@", [code]))
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        close()
    }
    
}

//网络请求
extension ZFOAuthViewController {
    
    func loadAcessToken(code:String) {
        WBNetworkManager.shared.loadAccessToken(code: code) { (json,success) in
            print("授权数据  加载 \((success ? "YES" : "NO"))")
        }
    }
    
}
